import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutterapp/Base/DemoUI/PageMain.dart';
import 'package:flutterapp/Base/Util/NavigatorObserver.dart';
import 'package:flutterapp/Base/PageTest.dart';
import 'package:flutterapp/Base/Util/ShakeManager.dart';
import 'package:flutterapp/Base/style/CusStyle.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'Base/Global.dart';
import 'Base/PageErr.dart';
import 'ServiceLocator.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'ServiceLocator.dart';
import 'request.dart' as res;
import 'mainList.dart' as mai;
//import 'dataBaseOpera.dart' as dat;
import 'fileSave.dart' as fil;
import 'package:audioplayers/audioplayers.dart';


void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Global.initApp().then((_) {
    setupLocator();
    // runApp(MyApp2());
    runApp(new Application());
  }).catchError((e) {
    print("===runApp fialed===  err=>$e");
  });
}

class Application extends StatefulWidget {
  @override
  _ApplicationState createState() => _ApplicationState();
}

class _ApplicationState extends State<Application> {
  var routeMap = {
    "/": (context) => PageTest(),
    PageMain.ROUTER_NAME:(context)=>PageMain(),
  };


  @override
  void initState() {
    super.initState();
    if (Global.ENV==PUBLISHING_ENVIRONMENT.DEV) {
      ShakeManager.getInstance().startListening();
    }
  }


  @override
  void dispose() {
    if (Global.ENV==PUBLISHING_ENVIRONMENT.DEV) {
      ShakeManager.getInstance().stopListening();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StoreProvider(
      store: Global.appStore,
      child: StoreBuilder(
        builder: (context, store) {
          return FlutterEasyLoading(
            child: MaterialApp(
                title: "flutterDemo",
                // initialRoute: "/",
                home: FormTest(),
                // routes: routeMap,
                theme: ThemeData(
//                  brightness: Brightness.dark,
                  primaryColor: CusColor.PRIMARY_COLOR,
                  accentColor: CusColor.SECOND_COLOR,
                ),
                navigatorObservers: [MyNavigatorObserver.getInstance()],
                onUnknownRoute: (settings) {
                  return PageRouteBuilder(pageBuilder: (context, __, ___) {
                    return PageErr();
                  });
                }),
          );
        },
      ),
    );
  }
}

class MyApp2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FormTest(),
    );
  }
}

class FormTest extends StatefulWidget {
  @override
  _FormTestState createState() => new _FormTestState();
}

class _FormTestState extends State<FormTest> {
  TextEditingController _unameController = new TextEditingController();
  TextEditingController _pwdController = new TextEditingController();
  GlobalKey _formKey= new GlobalKey<FormState>();
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  String platformVersion = "";
  BuildContext _context = null;
  String _regisId = "";
  bool remember = false;
  AudioPlayer audioPlayer = AudioPlayer();

  // 增加缓存
  _setValueByString(String key, String val) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(key, val);
  }

  // 对话框设置
  void showAlertDialog(BuildContext context, String msg) {
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Text(msg),
            title: Center(
                child: Text(
                  '标题',
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: 20.0,
                      fontWeight: FontWeight.bold),
                )),
            actions: <Widget>[
              FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('确定'))
            ],
          );
        });
  }

  // 通知被点击的监听方
  Future onSelectNotification(String payload) async {
    print('点击通知');
    Navigator.push(_context, MaterialPageRoute(builder: (_) {
      // 存缓存
      return new Scaffold(
        appBar: AppBar(title: Text('跳转页面'),),
        body: Text('12332112'),
      );
    }));
  }

  // 显示通知
  showNotification(String title, String content) async {
    var android = new AndroidNotificationDetails(
        'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
        priority: Priority.High,importance: Importance.Max
    );
    var iOS = new IOSNotificationDetails();
    var platform = new NotificationDetails(android, iOS);
    await flutterLocalNotificationsPlugin.show(
        0, title, content, platform,
        payload: 'Nitish Kumar Singh is part time Youtuber');
  }

  _init(BuildContext context) async {
    String sign = await fil.readCounter2();
    if (sign == null || sign== '' || sign == '0') {
      String userId = await fil.readCounter();
      if (userId != null && userId != "") {
        Navigator.push(context, MaterialPageRoute(builder: (_) {
          return mai.listState();
        }));
      }
    } else {
      String up = await fil.readCounter1();
      if (up != null && up != "") {
        List<String> arr = up.split("--");
        _unameController = new TextEditingController(text: arr[0]);
        _pwdController = new TextEditingController(text: arr[1]);
      }
    }
  }

  // 播放
  play() async {
    int result = await audioPlayer.play('neworder.mp3');
    if (result == 1) {
      // success
      print('play success');
    } else {
      print('play failed');
    }
  }

  ///根布局的初始化
  @override
  void initState() {
    super.initState();
//    var android = AndroidInitializationSettings('notify_icon');
//    var ios = IOSInitializationSettings();
//    var initSetting = InitializationSettings(android, ios);
//    flutterLocalNotificationsPlugin.initialize(initSetting, onSelectNotification: onSelectNotification);

    // 创建数据库
//    dat.create();

    ///创建 JPush
    ///
    JPush _jPush = new JPush();
    ///配置应用 Key
    _jPush.setup(
      appKey: "8324196e7cbf68a5bff8eb21",
      channel: "theChannel",
      production: false,
      /// 设置是否打印 debug 日志
      debug: true,
    );
    _jPush.getRegistrationID().then((value) => _regisId = value);
    try {
      _jPush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {
            play();
            // 弹出通知数据
//            showNotification(message['title'], message['extras']['cn.jpush.android.EXTRA']['content']);
          }
      );
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
  }

  @override
  Widget build(BuildContext context) {
    _init(context);
    return Scaffold(
      backgroundColor: Color.fromRGBO(72, 85, 99, 1),
      body:  GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: SingleChildScrollView(
          child: new Container(
//            decoration: new BoxDecoration(
//              gradient: LinearGradient(
//                  begin: Alignment(0.0, -1.0),
//                  end: Alignment(0.0, 1.0),
//                  colors: <Color>[Color.fromRGBO(72, 85, 99, 1),Color.fromRGBO(30, 30, 30, 1)]
//              ),
//            ),
//            padding: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 164.0),
            child: Column(
              children: <Widget>[
                new Center(
                    child: new Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          new Container(
                            child: new Image.asset('images/LOGO.png'),
                            width: 100.5,
                            height: 89,
                            margin: const EdgeInsets.fromLTRB(0.0, 50.5, 0.0, 0.0),
                          ),
                          new Text('邻客专送',
                            textDirection: TextDirection.ltr,
                            style: new TextStyle(fontSize: 41.0, color: Color.fromRGBO(255, 213, 140, 1), fontWeight: FontWeight.w400, fontFamily: 'SourceHanSansCN-Normal'),
                          ),
                          new Container(
                            child: new Text('注册登陆即可成为邻客骑手',
                                textDirection: TextDirection.ltr,
                                style: new TextStyle(fontSize: 18.0, color: Color.fromRGBO(255, 213, 140, 1), fontWeight: FontWeight.w100, fontFamily: 'SourceHanSansCN-ExtraLight')),
                            margin: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 20.0),
                          ),
                          new ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: Container(
                              width: 356,
                              height: 310,
                              color: Colors.white,
                              padding: EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 0.0),
                              child: new Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Form(
                                    key: _formKey, //设置globalKey，用于后面获取FormState
                                    autovalidate: true, //开启自动校验
                                    child: Column(
                                      children: <Widget>[
                                        TextFormField(
                                            autofocus: false,
                                            controller: _unameController,
                                            decoration: InputDecoration(
                                              labelText: "用户名",
                                              hintText: "您的用户名",
                                              icon: Icon(Icons.person),
//                                              border: InputBorder.none,//去掉输入框的下滑线
                                              fillColor: Color.fromRGBO(237, 237, 237, 1),
//                                              filled: true,
                                              contentPadding: const EdgeInsets.symmetric(vertical: 10.0),
                                            ),
                                            // 校验用户名
                                            validator: (v) {
                                              return v.trim().length > 0 ? null : "用户名不能为空";
                                            }

                                        ),
                                        TextFormField(
                                            controller: _pwdController,
                                            decoration: InputDecoration(
                                              labelText: "密码",
                                              hintText: "您的登录密码",
                                              icon: Icon(Icons.lock),
//                                            border: InputBorder.none,//去掉输入框的下滑线
                                              fillColor: Color.fromRGBO(237, 237, 237, 1),
//                                            filled: true,
                                            ),
                                            obscureText: true,
                                            //校验密码
                                            validator: (v) {
                                              return v.trim().length > 5 ? null : "密码不能少于6位";
                                            }
                                        ),
                                        // 登录按钮
                                        Padding(
                                          padding: const EdgeInsets.only(top: 28.0, bottom: 10.0),
                                          child: Row(
                                            children: <Widget>[
                                              Expanded(
                                                  child: Container(
                                                    child: Material(
                                                        child: Ink(
                                                          decoration: BoxDecoration(
                                                            color: Color.fromRGBO(255, 174, 0, 1),
                                                            //设置四周圆角 角度
                                                            borderRadius: BorderRadius.all(Radius.circular(10.0)),
                                                            //设置四周边框
                                                            border: new Border.all(width: 1, color: Color.fromRGBO(202, 172, 108, 1)),
                                                          ),
                                                          child: InkResponse(
                                                            borderRadius: new BorderRadius.all(new Radius.circular(10.0)),
                                                            //点击或者toch控件高亮时显示的控件在控件上层,水波纹下层
                                                            highlightColor: Colors.yellow,
                                                            //点击或者toch控件高亮的shape形状
                                                            highlightShape: BoxShape.rectangle,
                                                            //.InkResponse内部的radius这个需要注意的是，我们需要半径大于控件的宽，如果radius过小，显示的水波纹就是一个很小的圆，
                                                            //水波纹的半径
                                                            radius: 300.0,
                                                            //水波纹的颜色
                                                            splashColor: Colors.yellow,
                                                            //true表示要剪裁水波纹响应的界面   false不剪裁  如果控件是圆角不剪裁的话水波纹是矩形
                                                            containedInkWell: true,
                                                            //点击事件
                                                            onTap: () {
                                                              if((_formKey.currentState as FormState).validate()){
                                                                if(this.remember) {
                                                                  fil.writeCounter1(_unameController.text, _pwdController.text);
                                                                }
                                                                fil.writeCounter2('0');
                                                                res.getLogin(_unameController.text, _pwdController.text, _regisId).then((value) => {
                                                                  if(value['code'] == '0') {
                                                                    Navigator.push(context, MaterialPageRoute(builder: (_) {
                                                                      // 存sqlsite数据库
//                                                                       var data = new Map<String,dynamic>();
//                                                                       data["userId"] = value['id'];
//                                                                       data["token"] = value['token'];
//                                                                       // 存缓存
//                                                                       dat.getBook(1).then((value) => {
//                                                                         if (value != null) {
//                                                                           dat.update(data, 1)
//                                                                         } else {
//                                                                            data["Id"] = 1,
//                                                                            dat.insert(data)
//                                                                         }
//                                                                       });
                                                                      // 本地储存
//                                                                       _setValueByString('userId', value['id']);
//                                                                       _setValueByString('token', value['token']);

                                                                      // 文件储存
                                                                      fil.writeCounter(value['id']);
                                                                      return mai.listState();
                                                                    }))
                                                                  } else {
                                                                    showAlertDialog(context, value['msg'])
                                                                  }
                                                                });
                                                              }
                                                            },
                                                            child: Container(
                                                              //设置 child 居中
                                                              alignment: Alignment(0, 0),
                                                              height: 30,
                                                              child: Text('登陆', style: TextStyle(fontSize: 20)),
                                                            ),
                                                          ),
                                                        )
                                                    ),
                                                  )
//                                                ButtonTheme(
//                                                  minWidth: 150.0,//设置最小宽度
//                                                  height: 20.0,
//                                                  child: RaisedButton(
////                                                    padding: EdgeInsets.all(15.0),
//                                                    child: Text("登陆", style: TextStyle(fontSize: 20),),
//                                                    color: Color.fromRGBO(255, 174, 0, 1),
//                                                    textColor: Colors.white,
//                                                    onPressed: () async{
//                                                      // 通过_formKey.currentState 获取FormState后，
//                                                      // 调用validate()方法校验用户名密码是否合法，校验
//                                                      // 通过后再提交数据。
//                                                      if((_formKey.currentState as FormState).validate()){
//                                                       res.getLogin(_unameController.text, _pwdController.text, _regisId).then((value) => {
//                                                          if(value['code'] == '0') {
//                                                             Navigator.push(context, MaterialPageRoute(builder: (_) {
//                                                               // 存缓存
//                                                               _setValueByString('userId', value['id']);
//                                                               _setValueByString('token', value['token']);
//                                                               return mai.listState();
//                                                             }))
//                                                          } else {
//                                                            showAlertDialog(context, value['msg'])
//                                                          }
//                                                       });
//                                                      }
//                                                    },
//                                                  ),
//                                                )
                                              ),
                                            ],
                                          ),
                                        ),
                                        Text('道路千万条安全第一条', style: TextStyle(fontSize: 10, color: Color.fromRGBO(120, 120, 120, 1)),),
                                        Row(
                                          children: <Widget>[
                                            Spacer(),
                                            Checkbox(
                                              value: this.remember,
                                              onChanged: (bool value) {
                                                setState(() {
                                                  this.remember = value;
                                                });
                                              },
                                            ),
                                            Text('记住密码', style: TextStyle(fontSize: 15, color: Colors.black),),
                                          ],
                                        )
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          )
                        ]
                    )
                ),
              ],
            ),
          ),
        ),
        onTap: (){
          //点击空白处隐藏键盘
          FocusScope.of(context).requestFocus(FocusNode());
        },
      ),
//      resizeToAvoidBottomPadding: false,
    );
  }
}